#coding=utf-8

import json
import re
import importlib
from global_utils.http_protocol import HttpHelp
from global_utils import http_protocol
from global_utils.register_assert import AssertRegister
from global_utils.log import logger
from global_utils.parser_ws_config import WSCONFIG


class TestCase(object):    
    def __init__(self,case_id):
        self.rule=re.compile(r'\$.*?\$')
        self.case_id=case_id
        self.case_info=self._get_case(self.case_id)
    
    #获取测试用例  
    def _get_case(self,case_id):
        case_info=HttpHelp.get(WSCONFIG.get_case, parameter={"case_id":case_id})    
        logger.info("获取测试用例".decode("utf8")+"ID:%s" % (case_id,) )
        logger.info("测试用例信息:%s".decode("utf8") % (case_info.encode("utf8"),))
        
        case_info=http_protocol.to_dict(case_info)
        return case_info
        
    #处理请求头     
    def _handle_headers(self):    
        headers=self.case_info["data"]["headers"]
        return self._handle_method(headers,"handle_request_body")
        
    
    #处理请求报文   
    def _handle_body(self):
        request_body=self.case_info["data"]["requestBody"]
        return self._handle_method(request_body,"handle_request_body")


      
    def _handle_method(self,stay_info,handle_moudle):
        need_handle=re.findall(self.rule, stay_info)
        if len(need_handle)==0:
            return stay_info
        else:
            for re_match in need_handle:
                handles=json.loads(re_match.strip("$"))    
                handles_method=handles["method"]
                try:
                    handles_args=handles["args"]
                except Exception:
                    handles_args={}
                else:
                    handles_args=handles["args"]
                
                moudel_class=importlib.import_module("".join((handle_moudle,".",handles_method)))
                handles_class= AssertRegister.register(moudel_class, handles_method,"request_handle")(handles_args)
                replace_var=handles_class.request_handle()
                stay_info=stay_info.replace(re_match, replace_var)
            return  stay_info  
        
    #处理完成的测试用例
    @property
    def get_case(self):
        self.case_info["data"]["headers"]=self._handle_headers().encode("utf8")
        self.case_info["data"]["requestBody"]= self._handle_body().encode("utf8")
        return self.case_info

if __name__=="__main__":
    print TestCase(1).get_case
    